package com.leetcode.first50;

/**
 * Created by weishaofei on 2018/11/18.
 */
public class LeetCode0002 {

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) { val = x; }
     * }
     */

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(l1.val + l2.val);
        ListNode temp = null;
        result.next = temp;
        while (l1.next != null) {
            ListNode next = new ListNode(l1.next.val + l2.next.val);
            temp = next;
            l1 = l1.next;
            l2 = l2.next;
            next.next = temp;
        }
        return result;
    }

    public ListNode genNextNode(ListNode result, ListNode l1, ListNode l2) {
        if (l1.next != null) {
            return genNextNode(result, l1.next, l2.next);
        }
        result.val = l1.val + l2.val;
        if (result.next != null) {
            result.val += result.next.val;
        }
        if (result.val > 9) {
            int va = 1;
            result.val = result.val % 10;
            result.next = new ListNode(va);

        }
        return result;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        ListNode a = new ListNode(2);
        a.next = new ListNode(4);
        a.next.next = new ListNode(3);


        ListNode b = new ListNode(5);
        b.next = new ListNode(6);
        b.next.next = new ListNode(4);

        ListNode sum = sum(a, b);
        while (sum != null){
            System.out.println(sum.val);
            sum = sum.next;
        }
    }

    private static ListNode sum(ListNode a, ListNode b) {
        ListNode first = new ListNode(a.val + b.val);
        ListNode cur = first;
        ListNode temp = null;
        first.next = temp;
        ListNode ta = a.next;
        ListNode tb = b.next;
        while (ta != null || tb != null) {
            ta = ta == null ? new ListNode(0): ta;
            tb = tb == null ? new ListNode(0): tb;
            temp = new ListNode(ta.val + tb.val + cur.val / 10);
            cur.val = cur.val % 10;
            cur.next = temp;
            cur = temp;
            ta = ta.next;
            tb = tb.next;
        }
        if (cur.val / 10 > 0) {
            ListNode node = new ListNode(cur.val / 10);
            cur.val = cur.val % 10;
            cur.next = node;
            return first;
        }

        return first;
    }
}
